import router from './router'
import store from '../../store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式

const print = (...data: any[]) => {
  // console.log(...data)
}

router.beforeEach((to, from, next) => {
  NProgress.start()
  print('-----------> to path = ', to)
  if (store.getters.isLogin) {
    print('-----------> 0')
    if (to.path === '/login') {
      print('-----------> 1')
      next({ name: 'Home' })
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      print('-----------> 2')
      if (store.getters.isGetUser) {
        print('-----------> 3')
        next()
      } else {
        print('-----------> 4')
        store.dispatch('GET_USER_INFO').then(() => { // 拉取用户信息
          print('-----------> 5')
          next()
        }).catch(() => {
          print('-----------> 6')
          store.dispatch('FED_LOG_OUT')
          next({ path: '/' })
        })
      }
    }
  } else {
    print('-----------> 7')
    if (to.path !== '/login') {
      print('-----------> 8')
      next({ name: 'Login' })
      NProgress.done()
    } else {
      print('-----------> 9')
      next()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})
